package com.thinvent.recommend.manager.manager.impl;

import com.thinvent.recommend.manager.config.MinioProperties;
import com.thinvent.recommend.manager.manager.MinioStorageManager;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * Minio的manager管理类
 */
@Component
public class MinioStorageManagerImpl implements MinioStorageManager {
    private final MinioClient minioClient;
    private final String bucketName;

    public MinioStorageManagerImpl(MinioClient minioClient,
                                   MinioProperties props) {
        this.minioClient = minioClient;
        this.bucketName = props.getBucketName();
    }

    @Override
    public void upload(String objectName, InputStream data, String contentType) throws Exception {
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .stream(data, -1, 1024 * 1024)
                        .contentType(contentType)
                        .build()
        );
    }

    @Override
    public Path download(String objectName, Path targetPath) throws Exception {
        try (InputStream in = minioClient.getObject(
                GetObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .build()
        )) {
            Files.copy(in, targetPath);
            return targetPath;
        }
    }
}
